<?php

namespace app\models\system;

use app\models\Images;
use Yii;

/**
 * This is the model class for table "set_qrcode".
 *
 * @property int $id
 * @property string $images image id list
 * @property string $text tips text
 */
class SetQrcode extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'set_qrcode';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['text'], 'required'],
            [['images', 'text'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'images' => 'Images',
            'text' => 'Text',
        ];
    }

    public static function getLastOne()
    {
        $model = self::find()
            ->orderBy(['id' => SORT_DESC])
            ->one();

        if (!$model) {
            $model = new self();
        }

        // image
        if ($model->images) {
            $images = explode(',', $model->images);
            if (count($images)) {
                foreach ($images as &$i) {
                    $i = Images::findOne(['id' => $i]);
                }
                $model->images = $images;
            }
        }

        return $model;
    }

    public static function saveData($text, $images)
    {
        $model = self::getLastOne();
        $model->text = $text;

        if (is_array($images)) {
            $list = implode(',', $images);
            $model->images = $list;
        } else {
            $model->images = '';
        }

        return $model->save();
    }
}
